<script setup>
import {ref, reactive, getCurrentInstance, onMounted} from "vue";
// 方式1 导入api
import {login, getUserInfo, username, password} from "@/api/user.js";
// 方式2 通过全局实例获取（需要在main.js中全局注册）
const {proxy} = getCurrentInstance()

const loginFormRef = ref(null)
const loginForm = reactive({
    username: 'admin',
    password: '123'
})

const rules = {
    username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
    password: [{required: true, message: '请输入密码', trigger: 'blur'}]
}

let result = reactive({
    id: undefined,
    username: undefined,
    password: undefined
})

onMounted(async () => {
    // 方式2 使用全局挂载的axios
    // const res = await proxy.$http.get('/captcha/image')
    getUserInfo().then((res) => {
        result.id = res.data
    })

    proxy.$http.get('/test/username').then((res) => {
        result.username = res.data
    })

    password().then((res) => {
        result.password = res.data
    })
})

const handleLogin = async () => {
    try {
        // 验证表单
        await loginFormRef.value.validate();

        // 方式1 导入api
        // const res = await login(loginForm);

        // 保存token
        // localStorage.setItem('token', res.data.token);

        // ElMessage.success('登录成功');
        getUserInfo().then((res) => {
            result.id = res.data
        })
    } catch (error) {
        console.error(error)
    }
}
</script>

<template>
    <div class="login-container">
        <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="loginForm.password" type="password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleLogin">登录</el-button>
            </el-form-item>
        </el-form>
        <el-row>
            <el-col :span="8">id</el-col>
            <el-col :span="8">username</el-col>
            <el-col :span="8">password</el-col>
        </el-row>
        <el-row>
            <el-col :span="8">{{ result.id }}</el-col>
            <el-col :span="8">{{ result.username }}</el-col>
            <el-col :span="8">{{ result.password}}</el-col>
        </el-row>
    </div>
</template>

<style scoped>
.login-container {
    width: 350px;
    margin: 150px auto;
    padding: 20px;
    border: 1px solid #eaeaea;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
</style>
